package test3.backtracking;

import java.util.*;

/**
 * 46. 全排列
 * 给定一个 没有重复 数字的序列，返回其所有可能的全排列。
 * 示例:
 * <p>
 * 输入: [1,2,3]
 * 输出:
 * [
 * [1,2,3],
 * [1,3,2],
 * [2,1,3],
 * [2,3,1],
 * [3,1,2],
 * [3,2,1]
 * ]
 * 通过次数298,8
 * <p>
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/permutations
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */
public class Permutation {
    public static void main(String[] args) {
        int[] nums = new int[]{1, 1, 2};
        List<List<Integer>> permute = new Permutation().permuteUnique(nums);
        for (List<Integer> items : permute) {
            for (Integer item : items) {
                System.out.print(item);
            }
            System.out.println();

        }
    }


    /**
     * 数组中元素重复
     *
     * @param nums
     * @return
     */
    public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        boolean[] bs = new boolean[nums.length];
        permuteUnique(nums, bs, result, path);
        return result;
    }

    public void permuteUnique(int[] nums, boolean[] bs, List<List<Integer>> result, List<Integer> path) {
        if (nums.length == path.size()) {
            result.add(new ArrayList<>(path));
            return;
        }
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (!bs[i]) {
                if (map.containsKey(nums[i])) continue;
                map.put(nums[i], i);
                bs[i] = true;
                path.add(nums[i]);
                permuteUnique(nums, bs, result, path);
                path.remove(path.size() - 1);
                bs[i] = false;
            }
        }
    }

    /**
     * 数据中元素不重复
     *
     * @param nums
     * @return
     */
    public List<List<Integer>> permute(int[] nums) {
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> path = new ArrayList<>();
        boolean[] bs = new boolean[nums.length];
        permute(nums, bs, result, path);
        return result;
    }

    public void permute(int[] nums, boolean[] bs, List<List<Integer>> result, List<Integer> path) {
        if (nums.length == path.size()) {
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (!bs[i]) {
                bs[i] = true;
                path.add(nums[i]);
                permute(nums, bs, result, path);
                path.remove(path.size() - 1);
                bs[i] = false;
            }
        }
    }
}
